package com.yc.spring.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * Company 源辰信息
 *
 * @author navy
 * @date 2024/8/2
 * Email haijunzhou@hnit.edu.cn
 */
@Component
@Aspect
public class MyAspect {

    // 前置增强
    @Before("pointcut1()")
    // 接口注入
    public void log(JoinPoint joinPoint){
        System.out.println("joinPoint.getSignature() = " + joinPoint.getSignature());
        System.out.println("joinPoint.getArgs() = " + Arrays.toString(joinPoint.getArgs()));
        System.out.println("joinPoint.getTarget() = " + joinPoint.getTarget());
    }

    @After("execution(* com.yc.spring.demo.web.*.find*(..))")
    public void after(JoinPoint joinPoint){
        System.out.println("after 后置增强");
    }

    // 切点方法
    @Pointcut("execution(* com.yc.spring.demo..*.find*(..))")
    public void pointcut1(){}

    @AfterReturning("pointcut1()")
    public void afterReturning(JoinPoint joinPoint){
        System.out.println("afterReturning 返回增强");
    }
    @AfterThrowing("pointcut1()")
    public void afterThrowing(JoinPoint joinPoint){
        System.out.println("afterThrowing 异常增强");
    }

    /**
     * try{
     *                   前置增强
     *     业务方法()
     *                   返回增强
     * } catch (Excepting e){
     *                   异常增强
     * } finally {
     *                   后置增强
     * }
     *
     *  性能监控
     */

    @Around("pointcut1()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint){
        // proceedingJoinPoint 提供执行业务方法的方法
        // 1. 业务方法由增强方法执行
        // 2. 增强方法的返回值就是业务方法的返回值
        long time1 = System.currentTimeMillis();
        long time2 = 0;
        try {
            Object ret = proceedingJoinPoint.proceed();
            time2 = System.currentTimeMillis();
            return ret;
        } catch (Throwable e) {
            time2 = System.currentTimeMillis();
            throw new RuntimeException(e);
        } finally {
            System.out.println("环绕增强, 共耗时:" + ( time2 - time1));
        }
    }

}
